package com.entmanage.web.controller.monitor;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.entmanage.common.utils.SecurityUtils;
import com.entmanage.common.utils.ServletUtils;
import com.entmanage.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.entmanage.common.annotation.Log;
import com.entmanage.common.core.controller.BaseController;
import com.entmanage.common.core.domain.AjaxResult;
import com.entmanage.common.core.page.TableDataInfo;
import com.entmanage.common.enums.BusinessType;
import com.entmanage.common.utils.poi.ExcelUtil;
import com.entmanage.system.domain.SysOperLog;
import com.entmanage.system.service.ISysOperLogService;

/**
 * 操作日志记录
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/monitor/operlog")
public class SysOperlogController extends BaseController
{
    @Autowired
    private ISysOperLogService operLogService;

    @PreAuthorize("@ss.hasPermi('monitor:operlog:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysOperLog operLog)
    {
        startPage();
        List<SysOperLog> list = operLogService.selectOperLogList(operLog);
        return getDataTable(list);
    }

    @Log(title = "操作日志", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('monitor:operlog:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysOperLog operLog)
    {
        List<SysOperLog> list = operLogService.selectOperLogList(operLog);
        ExcelUtil<SysOperLog> util = new ExcelUtil<SysOperLog>(SysOperLog.class);
        util.exportExcel(response, list, "操作日志");
    }

    @Log(title = "操作日志", businessType = BusinessType.DELETE)
    @PreAuthorize("@ss.hasPermi('monitor:operlog:remove')")
    @DeleteMapping("/{operIds}")
    public AjaxResult remove(@PathVariable Long[] operIds)
    {
        return toAjax(operLogService.deleteOperLogByIds(operIds));
    }

    @Log(title = "操作日志", businessType = BusinessType.CLEAN)
    @PreAuthorize("@ss.hasPermi('monitor:operlog:remove')")
    @DeleteMapping("/clean")
    public AjaxResult clean()
    {
        operLogService.cleanOperLog();
        return success();
    }

    @PostMapping("/privacy-log")
    public AjaxResult recordPrivacyViewLog(@RequestBody Map<String, Object> payload, HttpServletRequest request) {
        try {
            // 从 Map 中安全获取参数
            Long empId = getLong(payload, "empId");
            String fieldName = getString(payload, "fieldName");
            String fieldLabel = getString(payload, "fieldLabel");

            // 参数校验（可选）
            if (empId == null || StringUtils.isEmpty(fieldName)) {
                // 即使参数不全，也静默忽略，不中断主流程
                logger.warn("隐私日志参数不全: {}", payload);
                return AjaxResult.success();
            }

            SysOperLog operLog = new SysOperLog();
            operLog.setTitle("隐私字段查看");
            operLog.setBusinessType(10);
            operLog.setMethod("SysOperlogController.recordPrivacyViewLog");
            operLog.setRequestMethod("POST");
            operLog.setOperatorType(1);
            operLog.setOperName(SecurityUtils.getUsername());
            operLog.setOperUrl("/monitor/operlog/privacy-log");
            operLog.setOperIp(getClientIP(request));
            operLog.setOperParam(String.format(
                    "查看员工ID=%s, 字段名=%s, 字段标签=%s",
                    empId,
                    fieldName,
                    fieldLabel
            ));
            operLog.setJsonResult("");
            operLog.setStatus(0);
            operLog.setErrorMsg("");
            operLog.setOperTime(new Date());
            operLog.setCostTime(0L);

            operLogService.insertOperlog(operLog);
        } catch (Exception e) {
            logger.warn("记录隐私查看日志失败，参数: {}, 错误: {}", payload, e.getMessage(), e);
        }
        return AjaxResult.success();
    }
    private String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
    @SuppressWarnings("unchecked")
    private Long getLong(Map<String, Object> map, String key) {
        Object val = map.get(key);
        if (val instanceof Integer) {
            return ((Integer) val).longValue();
        } else if (val instanceof Long) {
            return (Long) val;
        }
        return null;
    }

    private String getString(Map<String, Object> map, String key) {
        Object val = map.get(key);
        return val == null ? null : val.toString();
    }
}
